<template>
  <ContainerContent :pagination="false" inner @run="getCascadeList">
    <div class="cascade-view">
      <operation-bar
        :error="tipsValue.error"
        :warning="tipsValue.warning"
        :diff="diff"
        @save-config="openConfirmDialog(diff)"
        @fullscreen="enterFullscreen"
        @error-click="cascaderRef?.position('error')"
        @warning-click="cascaderRef?.position('warning')" />
      <div ref="cascadeWrap" class="cascade-wrap">
        <cdn-cascader
          ref="cascaderRef"
          v-model:diff="diff"
          v-model:tips="tipsValue"
          :data="dataSource || []"
          :isFullscreen="isFullscreen"
          @node-click="(_, node) => handleEditNode(node.node_id)">
          <template #exit-fullscreen>
            <header v-if="isFullscreen" class="cdn-cascader__header">
              <span class="text-[16px] font-bold">级联管理</span>
              <div class="flex-1"></div>
              <span class="exit-fullscreen">
                <a-button @click="exitFullscreen"> 退出全屏 </a-button>
              </span>
            </header>
          </template>
        </cdn-cascader>
      </div>
    </div>
    <confirm-dialog
      ref="confirmDialogRef"
      v-model:visible="confirmDialogVisible"
      v-model:record="confirmDialogRecord"
      :tips="tipsValue.risks"
      :diff-data="cascaderRef?.modelValue!"
      @save="getCascadeList"></confirm-dialog>
    <edit-node-dialog
      v-model:visible="editDialogVisible"
      v-model:record="editDialogData"
      @save="handleSaveSuccess" />
    <tips-video-dialog v-model:visible="tipsVideoDialogVisible" />
  </ContainerContent>
</template>

<script setup lang="ts">
import ContainerContent from '@/components/ContentContainer.vue'
import { useFullscreen } from '@vueuse/core'

import { type CascaderDiff, CdnCascader } from '@/components/Cascader'

import { useAppStore } from '@/stores/app'
import ConfirmDialog from './components/ConfirmDialog.vue'
import EditNodeDialog from './components/EditNodeDialog.vue'
import OperationBar from './components/OperationBar.vue'
import TipsVideoDialog from './components/TipsVideoDialog.vue'
import { getApiNodeCascadeRegionListApi } from '@/apis/modules/node/node'

const appStore = computed(() => useAppStore())

const {
  visible: confirmDialogVisible,
  data: confirmDialogRecord,
  open: openConfirmDialog
} = usePopup()

const {
  visible: editDialogVisible,
  data: editDialogData,
  open: openEditDialog
} = usePopup()

const { visible: tipsVideoDialogVisible, open: openTipsVideoDialog } =
  usePopup()
onMounted(() => {
  if (!appStore.value.nodeCascadeVideoTipsShowed) {
    openTipsVideoDialog()
  }
})

const data = ref({ charts: [] })
const { request: getCascadeList } = useRequest(getApiNodeCascadeRegionListApi, {
  success(res) {
    data.value.charts = res?.list?.map((item) => {
      return {
        region_id: item.id,
        region_name: item.name,
        node_L1:
          item.l1_nodes?.map((i) => ({
            node_id: i.id,
            node_name: i.name,
            region_id: i.region_id,
            region_name: item.name,
            node_ip: i.ips?.length ? i.ips[0] : i.ips?.toString(),
            run_status: i.status,
            resolve_status: i?.resolve_status,
            level: 1
          })) || [],
        node_L2:
          item.l2_nodes?.map((i) => ({
            node_id: i.id,
            node_name: i.name,
            region_id: i.region_id,
            region_name: item.name,
            node_ip: i.ips?.length ? i.ips[0] : i.ips?.toString(),
            run_status: i.status,
            resolve_status: i?.resolve_status,
            level: 2
          })) || []
      }
    })
  }
})

const cascaderRef = ref<InstanceType<typeof CdnCascader>>()

const diff = ref<CascaderDiff[]>([])
const dataSource = computed(() => {
  return data.value || { charts: [] }
})
const tipsValue = ref({
  error: 0,
  warning: 0,
  risks: [] as string[]
})
provide('tipsValue', tipsValue)

// 编辑节点保存成功
function handleSaveSuccess() {
  getCascadeList()
}

const confirmDialogRef = ref<InstanceType<typeof ConfirmDialog>>()
function handleEditNode(nodeId: string) {
  if (isFullscreen.value) return
  if (!diff.value.length) {
    return openEditDialog(nodeId)
  }
  CloudModal.confirm(
    {
      content: '您的操作尚未保存，确定要进行节点编辑？',
      okText: '保存并编辑'
    },
    async () => {
      await confirmDialogRef.value?.save(diff.value)
      diff.value = []
      ToastUtils.success('操作成功')
      openEditDialog(nodeId)
    }
  )
}

const cascadeWrap = ref()
const {
  isFullscreen,
  enter: enterFullscreen,
  exit: exitFullscreen
} = useFullscreen(cascadeWrap)
onMounted(getCascadeList)

const handleBeforeUnload = (event) => {
  if (diff.value.length) {
    event.preventDefault()
    // CloudModal.confirm(
    //   {
    //     content: '您的操作尚未保存，确定要刷新页面？',
    //     okText: '刷新'
    //   },
    //   async () => {
    //     window.location.reload()
    //   }
    // )
  }
}

onMounted(() => {
  window.addEventListener('beforeunload', handleBeforeUnload)
})

// 组件卸载时移除事件监听
onBeforeUnmount(() => {
  window.removeEventListener('beforeunload', handleBeforeUnload)
})

// 路由离开前触发
onBeforeRouteLeave((to, from, next) => {
  if (diff.value.length) {
    CloudModal.confirm(
      {
        content: '您的操作尚未保存，确定要离开页面？',
        okText: '离开'
      },
      async () => {
        next()
      }
    )
  } else {
    next()
  }
})
</script>

<style scoped lang="less">
.cascade-view {
  @apply bg-white h-full rounded-md flex flex-col;
  .cascade-wrap {
    @apply h-full overflow-hidden;
  }
}
</style>
